package brand

import (
	"context"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/spf13/cast"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetBrandListApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetBrandListApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetBrandListApiLogic {
	hostname, _ := os.Hostname()
	return &GetBrandListApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetBrandListApiLogic) GetBrandListApi() (resp []types.BrandListResp, err error) {
	enterpriseId := cast.ToInt64(l.ctx.Value("enterpriseId"))
	brandEntities, err := dao.BrandEntity.WithContext(l.ctx).Where(
		dao.BrandEntity.EnterpriseID.Eq(enterpriseId),
		dao.BrandEntity.Status.Eq(1),
	).Order(dao.BrandEntity.Sort, dao.BrandEntity.ID.Desc()).Find()
	if err != nil {
		l.Logger.Error("查询单位失败", err.Error())
		return make([]types.BrandListResp, 0), nil
	}
	brandListResps := k.Map(brandEntities, func(item *model.BrandEntity, index int) types.BrandListResp {
		return types.BrandListResp{
			ID:   item.ID,   // 主键id
			Name: item.Name, // 品牌名称
			Sort: item.Sort, // 排序
		}
	})
	return brandListResps, nil
}
